'use strict';
/** 直接代理保存网站 */
const http = require("http"), https = require("https"), fs = require("fs"), querystring = require("querystring");

module.exports = (request, response, rfun)=>{
    let op = {"host": "", "port": 80, "path": request.url };
    op.host = request.headers.host
    op.method = request.method;
    op.headers = request.headers;

    let req = http.request(op, (res)=>{
        if(res.headers['set-cookie']) response.setHeader("Set-Cookie", res.headers['set-cookie']);
        if(res.headers['last-modified']) response.setHeader("last-modified", res.headers['last-modified']);
        res.pipe(response);
        if(res.statusCode == 302){
            response.statusCode = res.statusCode;
            response.setHeader("location", res.headers["location"]);
            return;
        }
        if(res.statusCode == 304){
            response.statusCode = res.statusCode;
            return;
        }
        //保存网站内容
        let cd = Buffer.allocUnsafe(0)
        res.on("data", (chunk)=>{
            cd = Buffer.concat([cd, chunk], cd.length + chunk.length);
        });
        res.on("end", ()=>{
            if(res.statusCode == 200){
                const cdir = require("./cdir");
                cdir(request.SITE["root"], request.GET.pathname, ()=>{
                    if(request.GET.pathname.substr(-1, 1) == '/') request.GET.pathname += "index.html"; 
                    fs.writeFile(request.SITE["root"] + request.GET.pathname, cd, function(err){
                        if(err){
                            request.LOG.error("write file error", request.url, err);
                            return;
                        }
                        request.LOG.error("write end", request.url);
                    });
                });
            }else{
                request.LOG.error("request", request.url, res.statusCode);
            }
        });
    });
    req.on("error",(err)=>{
        request.LOG.error(request.url, err);
    });
    if(request.POSTBUF) req.write(request.POSTBUF);
    req.end();
}